const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const db = require('../config/database');

// 中间件：验证JWT token
const verifyToken = (req, res, next) => {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    if (!token) {
        return res.status(401).json({ msg: '未提供访问令牌' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        res.status(401).json({ msg: '无效的访问令牌' });
    }
};

// 获取消息列表
router.get('/', verifyToken, async (req, res) => {
    try {
        const [msgs] = await db.pool.query(
            'SELECT m.*, u.username FROM msgs m LEFT JOIN users u ON m.user_id = u.id WHERE m.user_id = ? ORDER BY m.created_at DESC',
            [req.user.id]
        );
        res.json({ code: 0, msg: '成功', data: msgs });
    } catch (error) {
        console.error('获取消息列表失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 发送消息
router.post('/', verifyToken, async (req, res) => {
    const { content, type } = req.body;

    if (!content) {
        return res.status(400).json({ code: -1, msg: '消息内容不能为空', data: {} });
    }

    try {
        const [result] = await db.pool.query(
            'INSERT INTO msgs (user_id, content, type) VALUES (?, ?, ?)',
            [req.user.id, content, type || 'text']
        );

        res.status(201).json({ code: 0, msg: '发送成功', data: {
            id: result.insertId,
            user_id: req.user.id,
            content,
            type: type || 'text',
            created_at: new Date()
        }});
    } catch (error) {
        console.error('发送消息失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 标记消息为已读
router.put('/:id/read', verifyToken, async (req, res) => {
    try {
        const [result] = await db.pool.query(
            'UPDATE msgs SET read_at = NOW() WHERE id = ? AND user_id = ? AND read_at IS NULL',
            [req.params.id, req.user.id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ code: -1, msg: '消息不存在或已读', data: {} });
        }

        res.json({ code: 0, msg: '消息已标记为已读', data: {} });
    } catch (error) {
        console.error('标记消息失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
    }
});

// 删除消息
router.delete('/:id', verifyToken, async (req, res) => {
    try {
        const [result] = await db.pool.query(
            'DELETE FROM msgs WHERE id = ? AND user_id = ?',
            [req.params.id, req.user.id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ code: -1, msg: '消息不存在', data: {}});
        }

        res.json({ code: 0, msg: '消息删除成功', data: {}});
    } catch (error) {
        console.error('删除消息失败:', error);
        res.status(500).json({ code: -1, msg: '服务器错误', data: {}});
    }
});

module.exports = router;